<template>
    <div class="enterprise-pc-login-setting">
        <div class="enterprise-title">
            <div class="enterprise-title-content">{{ $t('setting.enterprise.pcLogin.title') }}</div>
            <div class="enterprise-title-tip">{{ $t('setting.enterprise.pcLogin.tip1') }}</div>
        </div>
        <div class="enterprise-content">
            <div class="enterprise-content-title">展现形式</div>
            <el-radio-group v-model="backgroundType">
                <el-radio label="slice">标准模式</el-radio>
                <el-radio label="full">全屏模式</el-radio>
            </el-radio-group>
            <div class="background-picture-content">
                <div class="background-picture-content-left">
                    <div class="slice-content">
                        <div class="slice-content-item">
                            <div class="slice-content-item-title">{{ $t('setting.enterprise.pcLogin.titleBG') }}</div>
                            <div class="slice-content-item-upload">
                                <el-upload 
                                    class="upload-background-picture mar-r-12" 
                                    action="string" 
                                    accept="image/png,image/jpg,image/jpeg"
                                    :auto-upload="false"
                                    :on-change="(file, fileList) => changeBackgroundPictureUpload(file, fileList, (backgroundType === 'slice'? 1: 3))" 
                                    :fileList="(backgroundType === 'slice'? backgroundPictureFileList: fullPictureFileList)"
                                    :on-remove="handleBackgroundPicturRemove"
                                    :show-file-list="false"
                                >
                                    <el-button type="primary">{{ $t('common.base.clickForUploading') }}</el-button>
                                </el-upload>
                                <el-button type="text" @click="downloadImage((backgroundType === 'slice'? 1: 3))">{{ $t('setting.enterprise.pcLogin.download') }}</el-button>
                            </div>
                            <div class="slice-content-item-tip" v-if="backgroundType === 'slice'">
                                推荐深色背景图，上传的图片尺寸建议为3840*1160，宽度不要小于1920，大小不超过3M
                            </div>
                            <div class="slice-content-item-tip" v-else>
                                推荐深色背景图，上传的图片尺寸建议为3840*2160，尽可能不要有文字内容呈现，避免遮挡大小不超过5M
                            </div>
                        </div>
                        <div class="slice-content-item" v-if="backgroundType === 'slice'">
                            <div class="slice-content-item-title">底部信息图片</div>
                            <div class="slice-content-item-upload">
                                <el-upload 
                                    class="upload-background-picture mar-r-12" 
                                    action="string" 
                                    accept="image/png,image/jpg,image/jpeg"
                                    :auto-upload="false"
                                    :on-change="(file, fileList) => changeBackgroundPictureUpload(file, fileList, 2)" 
                                    :fileList="belowPictureFileList"
                                    :on-remove="handleBackgroundPicturRemove"
                                    :show-file-list="false"
                                >
                                    <el-button type="primary">{{ $t('common.base.clickForUploading') }}</el-button>
                                </el-upload>
                                <el-button type="text" @click="downloadImage(2)">{{ $t('setting.enterprise.pcLogin.download') }}</el-button>
                            </div>
                            <div class="slice-content-item-tip">推荐白色背景图，上传的图片尺寸建议为3840*540，宽度不要小于1920，大小不超过3M</div>
                        </div>
                    </div>
                </div>
                <div class="background-picture-content-right">
                    <div class="title">预览</div>
                    <loginPreview 
                        :backgroundType="backgroundType"
                        :backgroundPictureUrl="backgroundPictureUrl"
                        :belowPictureUrl="belowPictureUrl"
                        :fullPictureUrl="fullPictureUrl"
                    ></loginPreview>
                </div>
            </div>
        </div>
        <div class="enterprise-footer">
            <el-button type="primary" :disabled="!isCanSave" @click="savePcLogin">
                {{ $t('common.base.save') }}
            </el-button>
            <el-button v-if="isShowReset" @click="resetImage">
                {{ $t('common.base.reset') }}
            </el-button>
        </div>
    </div>
</template>

<script>
import { settingInfo } from '@src/modules/setting/common/enterprise/api';
import Uploader from 'packages/BaseUpload/uploader';
import { getRootWindow } from '@src/util/dom';
import { getOssUrl } from '@src/util/assets'
import loginPreview from './login_preview.vue';

export default {
    name: "pcLogin",
    props: {
        pcLoginPageSettingParam: {
            type: Object,
            default: () => {
                return {};
            }
        }
    },
    components: {
        loginPreview,
    },
    created() {
        this.backgroundType = this.pcLoginPageSettingParam?.backgroundType || 'slice';
        this.backgroundPictureUrl = this.pcLoginPageSettingParam?.backgroundPictureUrl || this.getDefaultBackgroundPicture();
        this.belowPictureUrl = this.pcLoginPageSettingParam?.belowPictureUrl || this.getDefaultBelowPicture();
        this.fullPictureUrl = this.pcLoginPageSettingParam?.fullPictureUrl || this.getDefaultFullPicture();
        this.oldBackgroundType = this.backgroundType;
        this.oldBackgroundPictureUrl = this.backgroundPictureUrl;
        this.oldBelowPictureUrl = this.belowPictureUrl;
        this.oldFullPictureUrl = this.fullPictureUrl;
    },
    data() {
        return {
            backgroundType: 'slice', // 背景图片显示类型
            backgroundPictureFileList: [],
            belowPictureFileList: [],
            fullPictureFileList: [],
            // slice下上面的背景图片
            backgroundPictureUrl: this.getDefaultBackgroundPicture(),
            // slice下下面的背景图片
            belowPictureUrl: this.getDefaultBelowPicture(),
            // full背景图片
            fullPictureUrl: this.getDefaultFullPicture(),
            // 从接口返回来的旧图片，当切换为另一类型时，原来类型中的图片需要用到旧图片
            oldBackgroundType: '',
            oldBackgroundPictureUrl: '',
            oldBelowPictureUrl: '',
            oldFullPictureUrl: '',
        }
    },
    computed: {
        isCanSave() {
            return (this.oldBackgroundType != this.backgroundType) ||
                (this.backgroundType === 'slice' ?
                this.backgroundPictureFileList.length > 0 || this.belowPictureFileList.length > 0 : 
                this.fullPictureFileList.length > 0)
        },
        isShowReset() {
            return this.backgroundPictureUrl !== this.getDefaultBackgroundPicture() || this.belowPictureUrl !== this.getDefaultBelowPicture() || this.fullPictureUrl !== this.getDefaultFullPicture();
        },
    },
    methods: {
        getDefaultBackgroundPicture() {
            return getOssUrl('/setting/pc_login.png');
        },
        getDefaultBelowPicture() {
            return getOssUrl('/setting/pc_login_buttom.jpg');
        },
        getDefaultFullPicture() {
            return getOssUrl('/setting/pc_login_full.jpg');
        },
        // 上传背景图片
        changeBackgroundPictureUpload(file, fileList, type) {
            // 检测文件类型
            if (file.raw.type !== 'image/jpeg' && file.raw.type !== 'image/png') {
                this.$message({
                    message: '上传图片格式仅为jpg/png',
                    duration: 1500,
                    type: 'error',
                });
                return;
            }
            // 检测图片大小，type为1，2时为3M以内，type为3时为5M以内
            if (file.raw.size > (type === 3 ? 5 : 3) * 1024 * 1024) {
                this.$message({
                    message: `上传图片大小不能超过${type === 3 ? 5 : 3}M`,
                    duration: 1500,
                    type: 'error',
                });
                return;
            }
            if (fileList.length > 1) {
                fileList.shift();
            }
            if (type === 1) {
                this.backgroundPictureFileList = fileList;
                this.backgroundPictureUrl = URL.createObjectURL(file.raw);
            } else if (type === 2) {
                this.belowPictureFileList = fileList;
                this.belowPictureUrl = URL.createObjectURL(file.raw);
            } else if (type === 3) {
                this.fullPictureFileList = fileList;
                this.fullPictureUrl = URL.createObjectURL(file.raw);
            }
        },
        // 移除中文背景图片
        handleBackgroundPicturRemove() {
            this.backgroundPictureUrl = this.getDefaultBackgroundPicture();
            this.backgroundPictureFileList = [];
        },
        // 下载示例图片
        downloadImage(type) {
            let imageUrl;
            if (type === 1) {
                imageUrl = getOssUrl('/setting/example.jpg');
            } else if (type === 2) {
                imageUrl = getOssUrl('/setting/example_buttom.jpg');
            } else if (type === 3) {
                imageUrl = getOssUrl('/setting/example_full.jpg');
            }
            fetch(imageUrl).then(res => res.blob()).then(blob => {
                const a = document.createElement('a');
                const url = window.URL.createObjectURL(blob);
                const filename = 'example.jpg';
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
                a.remove();
            });
        },
        // 重置背景图片
        resetImage() {
            settingInfo({
                pcLoginPageSettingParam: {
                    backgroundType: this.backgroundType,
                    backgroundPictureUrl: this.getDefaultBackgroundPicture(),
                    belowPictureUrl: this.getDefaultBelowPicture(),
                    fullPictureUrl: this.getDefaultFullPicture(),
                    enBackgroundPictureUrl: getOssUrl('/setting/pc_login_en.png'),
                },
                tenantId: JSON.parse(getRootWindow(window)._init).user.tenantId,
                type: '3'
            }).then(res => {
                if (res.status == 0) {
                    this.$message.success(this.$t('common.base.resetSuccess'));
                    this.oldBackgroundType = this.backgroundType;
                    this.backgroundPictureUrl = this.getDefaultBackgroundPicture();
                    this.belowPictureUrl = this.getDefaultBelowPicture();
                    this.fullPictureUrl = this.getDefaultFullPicture();
                    this.backgroundPictureFileList = [];
                    this.belowPictureFileList = [];
                    this.fullPictureFileList = [];
                    this.oldBackgroundPictureUrl = this.getDefaultBackgroundPicture();
                    this.oldBelowPictureUrl = this.getDefaultBelowPicture();
                    this.oldFullPictureUrl = this.getDefaultFullPicture()
                } else {
                    this.$message.error(res.message);
                }
            })
        },
        uploadPicture(raw) {
            return Uploader.upload(raw, '/files/upload').then(res => {
                if (res.status != 0) {
                    this.$message({
                        message: `${res.message}`,
                        duration: 1500,
                        type: 'error',
                    });
                    return;
                }
                let file = res.data;
                return file.ossUrl || file.url || `/files/get?fileId=${file.id}`;
            }).catch(err => {
                console.warn(err);
            });
        },
        // 保存
        savePcLogin() {
            let p1, p2, p3;
            if (this.backgroundType === 'slice' && this.backgroundPictureFileList.length > 0) {
                p1 = this.uploadPicture(this.backgroundPictureFileList[0].raw);
            } else {
                p1 = Promise.resolve(this.oldBackgroundPictureUrl);
            }
            if (this.backgroundType === 'slice' && this.belowPictureFileList.length > 0) {
                p2 = this.uploadPicture(this.belowPictureFileList[0].raw);
            } else {
                p2 = Promise.resolve(this.oldBelowPictureUrl);
            }
            if (this.backgroundType !== 'slice' && this.fullPictureFileList.length > 0) {
                p3 = this.uploadPicture(this.fullPictureFileList[0].raw);
            } else {
                p3 = Promise.resolve(this.oldFullPictureUrl);
            }
            
            Promise.all([p1, p2, p3]).then(res => {
                settingInfo({
                    pcLoginPageSettingParam: {
                        backgroundType: this.backgroundType,
                        backgroundPictureUrl: res[0],
                        belowPictureUrl: res[1],
                        fullPictureUrl: res[2],
                        enBackgroundPictureUrl: getOssUrl('/setting/pc_login_en.png'),
                    },
                    tenantId: JSON.parse(getRootWindow(window)._init).user.tenantId,
                    type: '3'
                }).then(result => {
                    if (result.status == 0) {
                        this.$message.success(this.$t('common.base.saveSuccess'));
                        this.oldBackgroundType = this.backgroundType;
                        this.backgroundPictureFileList = [];
                        this.belowPictureFileList = [];
                        this.fullPictureFileList = [];
                        this.backgroundPictureUrl = res[0];
                        this.belowPictureUrl = res[1];
                        this.fullPictureUrl = res[2];
                        this.oldBackgroundPictureUrl = res[0];
                        this.oldBelowPictureUrl = res[1];
                        this.oldFullPictureUrl = res[2];
                    } else {
                        this.$message.error(res.message);
                    }
                })
            }).catch(err => {
                console.warn(err);
            });
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .is-disabled {
    background-color: var(--color-primary-light-3) !important;
    border-color: var(--color-primary-light-3) !important;
}
::v-deep .is-disabled:hover {
    background-color: var(--color-primary-light-3) !important;
    border-color: var(--color-primary-light-3) !important;
}
.enterprise-pc-login-setting {
    width: 100%;
    background-color: #fff;
    margin-top: 12px;
    overflow: hidden;
    border-radius: 4px;

    .enterprise-title {
        display: flex;
        padding: 12px 16px;
        height: 50px;
        border-bottom: 1px solid #E4E7ED;

        &-content {
            font-size: 18px;
            font-weight: 500;
            color: #262626;
        }

        &-tip {
            font-size: 14px;
            font-weight: 400;
            color: #8C8C8C;
            line-height: 25px;
        }
    }

    .enterprise-content {
        padding: 16px;

        &-title {
            font-size: 14px;
            font-weight: 500;
            height: 32px;
            line-height: 32px;
        }

        .background-picture-content {
            padding-right: 32px;
            display: flex;

            &-left {
                width: 500px;
                margin-right: 16px;
                .slice-content {
                    &-item {
                        margin-top: 16px;
                        &-title {
                            height: 22px;
                            font-size: 14px;
                            font-weight: 500;
                        }
                        &-upload {
                            display: flex;
                            margin-top: 8px;
                        }
                        &-tip {
                            color: #8C8C8C;
                            font-size: 12px;
                            line-height: 20px;
                            margin-top: 8px;
                        }
                    }
                }
            }
            &-right {
                .title {
                    margin: 16px 0 4px;
                    height: 22px;
                    line-height: 22px;
                }
            }
        }
    }

    .enterprise-footer {
        padding: 0 16px 24px 16px;
        display: flex;
        align-items: center;
    }
}
</style>